package cn.edu.ctbu.websql.controller;
import cn.edu.ctbu.websql.domain.Result;
import cn.edu.ctbu.websql.domain.Course;
import cn.edu.ctbu.websql.helper.PageUtils;
import cn.edu.ctbu.websql.service.CourseService;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@Slf4j
@RestController
@RequestMapping(value = "/webapi/course")
public class CourseRestController {
    @Autowired
    private CourseService courseService;
    /**
     * 读取url：/webapi/students/list，显示学生列表
     * @return
     */
    @GetMapping("/list")
    public PageUtils GetAll(Integer limit, Integer page){
        Pageable pageable = PageRequest.of(page-1,limit);

        Page<Course> temCourse = courseService.getAll(pageable);
        PageUtils pageUtils = new PageUtils(temCourse.getTotalElements(),temCourse.getContent());
        return  pageUtils;
    }

    @DeleteMapping ("/delete/{id}")
    public void delete(@PathVariable Integer id){
        courseService.delete(id);
    }

    /**
     * 新增更新学生数据内容，url：/webapi/students/updata
     * @param id
     * @return
     */
    @PutMapping("/update/{id}")
    public Course update(@PathVariable Integer id,Course newCourse){
        // 在方法参数上使用 @Valid 注解，触发实体类的验证
        return courseService.update(id, newCourse);
    }
    @GetMapping("/getdata/{id}")
    public Optional<Course> getData(@PathVariable Integer id){
        return courseService.getData(id);
    }
    @GetMapping("/search/{no}")
    public List<Course> searchData(@PathVariable String no){
        return courseService.searchData(no);
    }

    @GetMapping("/list1")
    public Result GetAll(){
        List<Course> courses = courseService.findAll();
        Result result = new Result();
        result.setCode(200);
        result.setSuccess(true);
        result.setData(courses);
        result.setMsg("学生列表信息");
        return result;
    }

}
